package com.example.demo.service;

import com.example.demo.entity.User;
import com.example.demo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Array;
import java.util.*;

@Service
public class UserService {

    @Autowired
    UserRepository userRepository;


    public Map<String,Object> userLogin( String name,String password,HttpServletRequest request){
        Map<String,Object> map = new HashMap<String,Object>();
        List<User>  data = userRepository.findByUserName(name);
        if(data.size()>0){
            if( password.equals(data.get(0).getUserPassWord()) ){
                HttpSession session = request.getSession();
                session.setAttribute("user",data.get(0).getId());
                Map  userMap = new HashMap();
                userMap.put("id",data.get(0).getId());
                userMap.put("name",data.get(0).getUserName());
                map.put("status",0);
                map.put("message","登录成功");
                map.put("data",userMap);
            }
            else{
                map.put("status",10);
                map.put("errMsg","密码错误");
            }
        }
        else{
            map.put("status",10);
            map.put("errMsg","账户名不存在");
        }

        return map;
    }

    @Cacheable(cacheNames = {"user"})
    public User getUser(Integer id){
        User user = userRepository.findOne(id);
        return user;
    }

    public User insertUser(User user){
        User save =  userRepository.save(user);
        return save;
    }

    // 这是进行分页查询
    public Page<User> findUserPage(Integer page){
        Page<User> userPage;
        Pageable pageable = new PageRequest(page, 10, Sort.Direction.ASC, "id");
        userPage = userRepository.findAll(pageable);
        return userPage;
    }

}
